
app.factory("LazyService", ['$q', function ($q) {
    function LazyService() {
        this.loaded = []; //{url: , promise: }
    }
    LazyService.prototype = {
        js: function (url) {
            var selections = this.loaded.filter(function (e) { return e.url == url });
            if (selections.length > 0)
                return selections[0].promise;
            else {
                var deferred = $q.defer();
                this.loaded.push({ url: url, promise: deferred.promise });

                var script = document.createElement('script');
                script.type = "text/javascript";
                script.src = url;
                script.addEventListener('load', function (ev) {
                    deferred.resolve(ev);
                });
                script.addEventListener('error', function (ev) { deferred.reject(ev); });
                document.body.appendChild(script);
                return deferred.promise;
            }
        },
        css: function (url) {
            var selections = this.loaded.filter(function (e) { return e.url == url });
            if (selections.length > 0)
                return selections[0].promise;
            else {
                var deferred = $q.defer();
                this.loaded.push({ url: url, promise: deferred.promise });

                var link = document.createElement("link");
                link.type = "text/css";
                link.rel = "stylesheet";
                link.href = url;
                link.addEventListener('load', function (ev) {
                    deferred.resolve(ev);
                });
                link.addEventListener('error', function (ev) { deferred.reject(ev); });
                document.head.appendChild(link);
                return deferred.promise;
            }
        }
    }
    return new LazyService();
} ]);
